const { Sequelize, Model, DataTypes, Op } = require('sequelize');
const { host, port, user, password, database } = require('../config/config').mysql;

const mysql2 = require('mysql2');
const sequelize = new Sequelize(database, user, password, {
	host,
	port,
	dialect: 'mysql',
	dialectModule: mysql2,

	timezone: '+08:00',
	//logging: console.log,
	logging: false,
	/*
	//显示日志函数调用所有参数
	logging: (...msg) => console.log(msg),
	*/

	define: {
		//自动添加createdAt，updatedAt，deletedAt
		timestamps: true,
		createdAt: 'create_time',
		updatedAt: 'update_time',
		//删除数据时不删除数据，而是更新deletedAt字段，如果为true，则deletedAt不能为false
		paranoid: true,
		deletedAt: 'delete_time',
		//使用自定义表名，true表示允许使用自定义表名，未设置tableName时，默认表名为模型名，false表示表名为模型名后加s
		freezeTableName: true,

		engine: 'MYISAM'
	}
});

/*
const sequelize = new Sequelize(`mysql://${user}:${password}@${host}:${port}/${database}`);
*/
sequelize.authenticate()
	.then(() => {
		console.log('Connection has been established successfully.');
	})
	.catch((error) => {
		console.error('Unable to connect to the database:', error);
	})

const AccessToken = sequelize.define('AccessToken', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	app_id: { type: DataTypes.STRING(50) },
	access_token: { type: DataTypes.STRING(500) },
	expires_time: { type: DataTypes.DATE },
	ticket: { type: DataTypes.STRING(500) },
}, {
	tableName: 'app_access_token',
	sequelize
});

class User extends Model { }
User.init({
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	username: {
		type: DataTypes.STRING(100)
	},
	password: {
		type: DataTypes.STRING(50)
	},
	role_id: {
		type: DataTypes.INTEGER, defaultValue: 0
	},
	fullname: {
		type: DataTypes.STRING(100)
	},
	nickname: {
		type: DataTypes.STRING(50)
	},
	head_img_url: {
		type: DataTypes.STRING(250)
	},
	birthday: {
		//type: DataTypes.DATEONLY
		type: DataTypes.STRING(10)
	},
	gender: {
		type: DataTypes.TINYINT,
		set(value) {
			this.setDataValue('gender', parseInt(value));
		}
	},
	email: {
		type: DataTypes.STRING(200)
	},
	phone: {
		type: DataTypes.STRING(11)
	},
	status: {
		type: DataTypes.INTEGER, defaultValue: 1,
		set(value) {
			this.setDataValue('status', parseInt(value));
		}
	},

	//团队ID（0公司直属，!0数字推广官）
	team_id: {
		type: DataTypes.INTEGER, defaultValue: 0,
		set(value) {
			this.setDataValue('team_id', parseInt(value));
		}
	},
	//推荐人ID
	tree_id: {
		type: DataTypes.INTEGER, defaultValue: 0,
		set(value) {
			this.setDataValue('tree_id', parseInt(value));
		}
	},
	open_id: {
		type: DataTypes.STRING(100)
	},
	url_scheme: {
		type: DataTypes.STRING(200)
	},
	//个人推广链接有效截至日期
	url_scheme_expired: {
		type: DataTypes.DATE
	},

	//推荐人备注
	tree_remark: {
		type: DataTypes.STRING(500)
	},
	//数字推广官备注
	team_remark: {
		type: DataTypes.STRING(500)
	},
	//账户余额
	balance: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0
	}
}, {
	tableName: 'app_user',
	sequelize,
	modelName: 'User'
});

const Profile = sequelize.define('Profile', {
	'id_card_no': { type: DataTypes.STRING(18) }
}, {
	tableName: 'app_profile',
	sequelize
});
/*
一个用户有一个详情表，一个详情表只属于一个用户
foreignKey外键user_id在app_profile中，因此app_profile为从表，app_user为主表
从表belongsTo|BelongsToMany 主表，主表hasMany|hasOne从表
*/
User.hasOne(Profile, {
	as: 'profile',
	foreignKey: 'user_id'
});
Profile.belongsTo(User, {
	as: 'user',
	foreignKey: 'user_id'
});

/*
const Company = sequelize.define('Company', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(100) }
}, {
	tableName: 'app_company',
	sequelize
});

//一个用户只属于一个公司，foreignKey外键company_id在app_user表中，从表为app_user，主表为app_company。
//从表belongsTo主表，主表hasMany|hasOne从表
User.belongsTo(Company, {
	as: 'company',
	foreignKey: 'company_id'
});
//一个公司有多个多个用户
Company.hasMany(User, {
	as: 'user',
	foreignKey: 'company_id'
});
*/

User.belongsTo(User, {
	as: 'tree_parent',
	foreignKey: {
		name: 'tree_id'
	},
	//关闭外键检查（tree_id=0）
	constraints: false
});
User.belongsTo(User, {
	as: 'team_parent',
	foreignKey: {
		name: 'team_id'
	},
	constraints: false
});


//数据字典
const Dictionary = sequelize.define('Dictionary', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(50) },
	code: { type: DataTypes.STRING(50) },
	parent_id: { type: DataTypes.INTEGER, defaultValue: 0 },
	parent_ids: { type: DataTypes.STRING(200) },
	memo: { type: DataTypes.STRING(200) },
	model: { type: DataTypes.JSON },

	//缩略图
	image: { type: DataTypes.STRING(250) }
}, {
	tableName: 'app_dictionary',
	sequelize
});

//车辆分类->工况
const CarCategoryWork = sequelize.define('CarCategoryWork', {
	/*
	id: {
		type: DataTypes.INTEGER,
		primaryKey: true,
		autoIncrement: true,
		allowNull: false
	}
	*/
}, { tableName: 'app_car_category_work', paranoid: false, sequelize });
Dictionary.belongsToMany(Dictionary, { through: CarCategoryWork, as: 'works', foreignKey: 'category_id', otherKey: 'work_id' });

const Region = sequelize.define('Region', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(50) },
	parent_id: { type: DataTypes.INTEGER, defaultValue: 0 },
	level: { type: DataTypes.INTEGER, defaultValue: 1 },
	sort: {
		type: DataTypes.INTEGER, defaultValue: 0,
		set(value) {
			this.setDataValue('sort', parseInt(value));
		}
	}
}, {
	tableName: 'app_region',
	sequelize
});

Region.hasMany(Region, {
	as: 'children',
	foreignKey: {
		name: 'parent_id'
	},
	constraints: false
});

const Config = sequelize.define('Config', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	//系统名称
	app_name: { type: DataTypes.STRING(100) },
	//企业logo
	logo: { type: DataTypes.STRING(250) },
	//推广背景图片
	promotion_bgImage: { type: DataTypes.STRING(250) },
	//推广海报图片
	promotion_posterImage: { type: DataTypes.STRING(250) },
	//服务背景图片
	service_bgImage: { type: DataTypes.STRING(250) },
	//隐私条款
	privacy: { type: DataTypes.TEXT },
	//服务条款
	term: { type: DataTypes.TEXT },
	//购买注意事项
	order_attention: { type: DataTypes.TEXT },
	//是否开启
	is_coupon: {
		type: DataTypes.TINYINT,
		defaultValue: 0,
		set(value) {
			this.setDataValue('is_coupon', parseInt(value));
		}
	},
	coupon_name: { type: DataTypes.STRING(250) },
	coupon_amount: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0,
		set(value) {
			this.setDataValue('coupon_amount', parseFloat(value));
		}
	},
	coupon_intro: { type: DataTypes.STRING(250) },

	//用户中心广告图
	ad_image: { type: DataTypes.STRING(200) },
	ad_url: { type: DataTypes.STRING(200) },

	//平台简介
	about: { type: DataTypes.TEXT },

	//权益升级
	benefit: { type: DataTypes.TEXT },
	//提现规则
	withdrawal: { type: DataTypes.TEXT },

}, {
	tableName: 'app_config',
	sequelize
});

const Industry = sequelize.define('Industry', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(100) },
	category1: { type: DataTypes.STRING(10) },
	category2: { type: DataTypes.STRING(20) },
	category3: { type: DataTypes.STRING(20) },
	category4: { type: DataTypes.STRING(20) },
	parent_id: { type: DataTypes.INTEGER, defaultValue: 0 },
	memo: { type: DataTypes.STRING(250) }
}, {
	tableName: 'app_industry',
	sequelize
});

Industry.hasMany(Industry, {
	as: 'children',
	foreignKey: {
		name: 'parent_id'
	}
});

//资讯
const Article = sequelize.define('Article', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	title: { type: DataTypes.STRING(250) },
	description: { type: DataTypes.STRING(250) },
	category_id: { type: DataTypes.INTEGER, defaultValue: 0 },
	images: { type: DataTypes.TEXT },
	share_image: { type: DataTypes.STRING(250) },
	content: { type: DataTypes.TEXT },
	pv: { type: DataTypes.INTEGER, defaultValue: 0 },
	is_top: {
		type: DataTypes.INTEGER,
		defaultValue: 0,
		set(value) {
			this.setDataValue('is_top', parseInt(value));
		},
		get() {
			return parseInt(this.getDataValue('is_top'));
		}
	},
	sort: {
		type: DataTypes.INTEGER, defaultValue: 0,
		set(value) {
			this.setDataValue('sort', parseInt(value));
		},
		get() {
			return parseInt(this.getDataValue('sort'));
		}
	},
	status: {
		type: DataTypes.INTEGER, defaultValue: 1,
		set(value) {
			this.setDataValue('status', parseInt(value));
		},
	},

	//车辆分类
	car_category_id: {
		type: DataTypes.INTEGER, defaultValue: 0
	},
	//视频
	video_poster: {
		type: DataTypes.STRING(500)
	},
	video_src: {
		type: DataTypes.STRING(500)
	},
	//装饰（exterior，interior）
	trim: {
		type: DataTypes.STRING(20)
	}
}, {
	tableName: 'app_article',
	sequelize
});

//用户有一个详细信息=>User.id=UserProfile.user_id=>User.hasOne(UserProfile) || UserProfile.belongsTo(User)
//Department.company_id=Company.id => Company.hasMany(Department)

Article.belongsTo(Dictionary, {
	as: 'category',
	foreignKey: {
		name: 'category_id'
	}
})

//驾校
const School = sequelize.define('School', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(250) },
	price: { type: DataTypes.DECIMAL(10, 2) },
	address: { type: DataTypes.STRING(500) },
	images: { type: DataTypes.TEXT },
	content: { type: DataTypes.TEXT }
}, {
	tableName: 'app_school',
	sequelize
});

//驾校所在地区
School.belongsTo(Region, {
	as: 'province',
	foreignKey: {
		name: 'province_id'
	}
});
School.belongsTo(Region, {
	as: 'city',
	foreignKey: {
		name: 'city_id'
	}
});

//驾校班型
const SchoolClass = sequelize.define('SchoolClass', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(250) },
	price: { type: DataTypes.DECIMAL(10, 2) },
	description: { type: DataTypes.STRING(500) }
}, {
	tableName: 'app_school_class',
	sequelize
});

School.Classes = School.hasMany(SchoolClass, {
	as: 'classes',
	foreignKey: {
		name: 'school_id'
	}
});

//驾校场地

const Doc = sequelize.define('Doc', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	title: { type: DataTypes.STRING(250) },
	description: { type: DataTypes.STRING(250) },
	size: { type: DataTypes.INTEGER, defaultValue: 0 },
	url: { type: DataTypes.STRING(250) }
}, {
	tableName: 'app_doc',
	sequelize
});
Doc.belongsTo(Dictionary, {
	as: 'category',
	foreignKey: {
		name: 'category_id'
	}
})

const Car = sequelize.define('Car', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(250) },
	version: { type: DataTypes.STRING(250) },

	description: { type: DataTypes.STRING(250) },

	//封面图
	cover: { type: DataTypes.STRING(250) },
	//缩略图
	thumb: { type: DataTypes.STRING(250) },
	//图集
	gallery: { type: DataTypes.TEXT },
	//详情内容
	content: { type: DataTypes.TEXT },
	//详情url
	detail_url: { type: DataTypes.STRING(250) },

	//规格内容
	model: { type: DataTypes.TEXT },
	//规格url
	model_url: { type: DataTypes.STRING(250) },

	//全国统一零售价
	retail_price: {
		type: DataTypes.DECIMAL(10, 2),
		set(value) {
			this.setDataValue('retail_price', parseFloat(value));
		}
	},
	//平台价
	price: {
		type: DataTypes.DECIMAL(10, 2),
		set(value) {
			this.setDataValue('price', parseFloat(value));
		}
	},
	//重要参数
	params: {
		type: DataTypes.JSON
	},

	//推荐奖
	award: {
		type: DataTypes.DECIMAL(10, 2)
	},
	//分佣
	commission: {
		type: DataTypes.DECIMAL(10, 2)
	},
	//分红
	bonus: {
		type: DataTypes.DECIMAL(10, 2)
	},
	//是否上传行驶证
	is_license: {
		type: DataTypes.TINYINT,
		defaultValue: 1
	},
	//定金金额
	deposit: {
		type: DataTypes.DECIMAL(10, 2)
	},

	region: {
		type: DataTypes.JSON
	},
	_region: {
		type: DataTypes.JSON,
		set(value) {
			this.setDataValue('_region', value || null);
		}
	}
}, {
	tableName: 'app_car',
	sequelize
});
Car.belongsTo(Dictionary, {
	as: 'category',
	foreignKey: {
		name: 'category_id'
	}
});
Car.belongsTo(User, {
	as: 'supplier',
	foreignKey: {
		name: 'supplier_id'
	},
	//不是所有的商品都有供应商
	constraints: false
});

//车辆规格
const CarModel = sequelize.define('CarModel', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	//分组
	group_id: {
		type: DataTypes.TINYINT,
		defaultValue: 1,
		set(value) {
			this.setDataValue('group_id', parseInt(value));
		}
	},
	//配置项
	name: { type: DataTypes.STRING(250) },
	//缩略图
	thumb: { type: DataTypes.STRING(250) },
	//全国统一零售价
	retail_price: {
		type: DataTypes.DECIMAL(10, 2),
		set(value) {
			this.setDataValue('retail_price', parseFloat(value));
		}
	},
	//平台价
	price: {
		type: DataTypes.DECIMAL(10, 2),
		set(value) {
			this.setDataValue('price', parseFloat(value));
		}
	}
}, {
	tableName: 'app_car_model',
	sequelize
});

//include: {association: Car.Models}
Car.Models = Car.hasMany(CarModel, {
	as: 'models',
	foreignKey: {
		name: 'car_id'
	}
});

const Station = sequelize.define('Station', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(250) },
	code: { type: DataTypes.STRING(250) },
	address: { type: DataTypes.STRING(500) },
	region: { type: DataTypes.JSON },
	level: { type: DataTypes.STRING(50) },
	serie: { type: DataTypes.STRING(50) },
	tel: { type: DataTypes.STRING(20) },
	access_time: {
		type: DataTypes.DATEONLY,
		set(value) {
			if (value) this.setDataValue('access_time', value);
		}
	},
	contact: { type: DataTypes.STRING(20) },
	phone: { type: DataTypes.STRING(20) },
	manufactor: { type: DataTypes.STRING(100) },
	auth_contact: { type: DataTypes.STRING(20) },
	auth_phone: { type: DataTypes.STRING(20) },
	status: {
		type: DataTypes.INTEGER, defaultValue: 1,
		set(value) {
			this.setDataValue('status', parseInt(value));
		}
	},
	sort: {
		type: DataTypes.TINYINT, defaultValue: 0,
		set(value) {
			this.setDataValue('sort', parseInt(value));
		}
	}

}, {
	tableName: 'app_station',
	sequelize
});


//角色管理
const Role = sequelize.define('Role', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(50) },
	auth: { type: DataTypes.JSON }
}, { tableName: 'app_role', sequelize });

User.belongsTo(Role, {
	as: 'role',
	foreignKey: 'role_id'
});

const Module = sequelize.define('Module', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	title: { type: DataTypes.STRING(50) },
	name: { type: DataTypes.STRING(50) },
	path: { type: DataTypes.STRING(100) },
	parent_id: {
		type: DataTypes.INTEGER,
		defaultValue: 0,
		set(value) {
			this.setDataValue('parent_id', parseInt(value));
		}
	},
	parent_ids: { type: DataTypes.STRING(250) },
	icon: { type: DataTypes.STRING(50) },
	component: { type: DataTypes.STRING(100) },
	sort: { type: DataTypes.TINYINT, defaultValue: 0 },
	status: { type: DataTypes.TINYINT },
	//类型：1菜单 2按钮
	type: {
		type: DataTypes.INTEGER,
		defaultValue: 1,
		set(value) {
			this.setDataValue('type', parseInt(value ?? 1));
		}
	},
	is_visible: {
		type: DataTypes.TINYINT,
		defaultValue: 1,
		set(value) {
			this.setDataValue('is_visible', parseInt(value ?? 1));
		}
	}
}, {
	tableName: 'app_module',
	defaultScope: {
		attributes: {
			exclude: ['create_time', 'update_time', 'delete_time']
		}
	},
	scopes: {
		actived: {
			where: {
				status: 1
			}
		}
	}, sequelize
});

/*
const Department = sequelize.define('Department', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(50) }
}, { tableName: 'app_department', sequelize });
*/

/*
//方案一
const UserDepartment = sequelize.define('UserDepartment', {
	id: {
		type: DataTypes.INTEGER,
		primaryKey: true,
		autoIncrement: true,
		allowNull: false
	}
}, { tableName: 'app_user_department', sequelize });

User.belongsToMany(Department, { through: UserDepartment, foreignKey: 'user_id', otherKey: 'department_id' });

//User include UserDepartment
User.hasMany(UserDepartment, { foreignKey: 'user_id' });

//UserDepartment include Department
UserDepartment.belongsTo(Department, { foreignKey: 'department_id' });

const UserDepartmentRole = sequelize.define('UserDepartmentRole', {
	id: {
		type: DataTypes.INTEGER,
		primaryKey: true,
		autoIncrement: true,
		allowNull: false
	}
}, { tableName: 'app_user_department_role', sequelize });

//UserDepartment include Role
UserDepartment.belongsToMany(Role, { through: UserDepartmentRole, foreignKey: 'user_department_id', otherKey: 'role_id' });
*/

//方案二
/*
const UserDepartmentRole = sequelize.define('UserDepartmentRole', {
	id: {
		type: DataTypes.INTEGER,
		primaryKey: true,
		autoIncrement: true,
		allowNull: false
	},
}, { tableName: 'app_user_department', timestamps: false, sequelize });

User.belongsToMany(Department, {
	through: UserDepartmentRole,
	uniqueKey: 'id',
	foreignKey: 'user_id', otherKey: 'department_id'
});
User.belongsToMany(Role, {
	through: UserDepartmentRole,
	uniqueKey: 'id',
	foreignKey: 'user_id', otherKey: 'role_id'
});

//User include UserDepartmentRole
User.hasMany(UserDepartmentRole, { foreignKey: 'user_id' });

//UserDepartmentRole include Department
UserDepartmentRole.belongsTo(Department, { foreignKey: 'department_id' });
UserDepartmentRole.belongsTo(Role, { foreignKey: 'role_id' });
*/

//一个用户归属于不同部门，不同部门有不同的角色
/*
const UserDepartmentRole = sequelize.define('UserDepartmentRole', {
	role_id: { type: DataTypes.INTEGER, defaultValue: 0 },
}, { tableName: 'app_user_department', timestamps: false, sequelize });
*/

/*
User.Role = User.belongsToMany(Role, {
	through: UserDepartmentRole,
	as: 'roles',
	foreignKey: 'user_id',
	otherKey: 'role_id'
});

User.belongsToMany(Department, {
	through: UserDepartmentRole,
	as: 'departments',
	foreignKey: 'user_id',
	otherKey: 'department_id'
});

User.hasMany(UserDepartmentRole, {
	foreignKey: 'user_id'
});

UserDepartmentRole.belongsTo(Department, {
	foreignKey: 'department_id'
});
UserDepartmentRole.belongsTo(Role, {
	foreignKey: 'role_id'
});
*/

const Coupon = sequelize.define('Coupon', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	name: { type: DataTypes.STRING(100) },
	amount: { type: DataTypes.DECIMAL(10, 2), defaultValue: 0 }
}, { tableName: 'app_coupon', sequelize });

/*
1. 一对一（hasOne，belongsTo）
user和profile，一个用户只有一个详情表。user_id在profile表中，因此user_id为外键，profile为从表，user为主表；
user hasOne profile，profile belongsTo user。

2. 一对多（hasMany，belongsTo）
user和article，一个用户有多篇文章，一篇文章只属于一个用户。user_id在article表中，因此article为从表，user为主表；
user hasMany article，article belongsTo user。

3. 多对多（只能使用belongsToMany）
user和coupon，一个用户有多个优惠券，一个优惠券又属于多个用户。
*/

const UserCoupon = sequelize.define('UserCoupon', {
	//是否使用
	status: { type: DataTypes.TINYINT, defaultValue: 0 }
}, { tableName: 'app_user_coupon', timestamps: false, sequelize });

//401的房东是W，402的房东也是W，那么W属于多个房间（401,402）的房东。
//用户1属于（是）多个优惠券的所有者，user通过user_coupon中的user_id（外键）进行连接
User.Coupon = User.belongsToMany(Coupon, {
	through: UserCoupon,
	as: 'coupons',
	foreignKey: 'user_id',
	otherKey: 'coupon_id'
});

const Order = sequelize.define('Order', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	//订单编号
	out_trade_no: { type: DataTypes.STRING(100) },
	//数量
	quantity: { type: DataTypes.INTEGER, defaultValue: 0 },
	//总价
	total_price: { type: DataTypes.DECIMAL(10, 2), defaultValue: 0 },
	//下单人
	user_id: { type: DataTypes.INTEGER, defaultValue: 0 },
	//车辆
	car_id: { type: DataTypes.INTEGER, defaultValue: 0 },
	//车辆单价
	price: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0
	},
	//选配
	car_model: {
		type: DataTypes.JSON,
		set(value) {
			this.setDataValue('car_model', value || null);
		}
	},
	//选配总价
	car_model_price: {
		type: DataTypes.DECIMAL(10, 2), defaultValue: 0
	},

	//用户类型
	user_type: {
		type: DataTypes.TINYINT,
		//1：个人，2：企业
		defaultValue: 1,
	},

	//联系人
	contact: { type: DataTypes.STRING(50) },
	//联系电话
	phone: { type: DataTypes.STRING(50) },
	//身份证
	id_card_no: { type: DataTypes.STRING(50) },

	//企业名称
	company: { type: DataTypes.STRING(100) },
	//统一社会信用代码
	uscc: { type: DataTypes.STRING(100) },

	//上牌城市
	reg_city: {
		type: DataTypes.JSON,
		set(value) {
			this.setDataValue('reg_city', value || null);
		}
	},
	_reg_city: {
		type: DataTypes.JSON,
		set(value) {
			this.setDataValue('_reg_city', value || null);
		}
	},

	//优惠信息（平台优惠一个用户只能用一次）
	coupon: { type: DataTypes.JSON },
	coupon_amount: { type: DataTypes.DECIMAL(10, 2) },

	//订单状态（0：未处理，1：排产中，2：已交付，3：已完成）
	status: { type: DataTypes.TINYINT, defaultValue: 0 },
	//支付状态（0：未支付，1：已支付）
	pay_status: { type: DataTypes.TINYINT, defaultValue: 0 },
	//支付时间
	pay_time: {
		type: DataTypes.DATE,
		set(value) {
			this.setDataValue('pay_time', value || null);
		}
	},
	//首次付款金额
	pay_amount: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0
	},
	//定金凭证
	deposit_receipt: {
		type: DataTypes.STRING(200)
	},

	//提车方式（1：来厂提车，2：送车上门）
	delivery_type: { type: DataTypes.TINYINT, defaultValue: 0 },

	//定金
	deposit: { type: DataTypes.DECIMAL(10, 2), defaultValue: 0 },

	//交付时间（尾款支付时间）
	delivery_time: {
		type: DataTypes.DATE,
		set(value) {
			this.setDataValue('delivery_time', value || null);
		}
	},
	//优惠金额
	discount: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0,
		set(value) {
			this.setDataValue('discount', parseFloat(value));
		}
	},

	//是否草稿（代客下单）
	is_draft: {
		type: DataTypes.TINYINT, defaultValue: 0
	},
	//代客下单用户
	draft_user_id: {
		type: DataTypes.INTEGER
	},
	//待客下单链接码（短链）
	draft_code: {
		type: DataTypes.STRING(20)
	},
	//是否购物车
	is_cart: {
		type: DataTypes.TINYINT, defaultValue: 0
	},

	//车辆行驶证
	car_license: {
		type: DataTypes.STRING(200)
	},

	//支付凭证
	pay_receipt: {
		type: DataTypes.STRING(200)
	},

	//购车合同
	contract: {
		type: DataTypes.STRING(200)
	},

	//购车发票
	invoice: {
		type: DataTypes.STRING(200)
	},

	//车辆合格证
	car_certificate: {
		type: DataTypes.STRING(200)
	},

	//车架号
	vin: {
		type: DataTypes.STRING(500)
	},

	//购物车合并支付ID
	pay_union_id: {
		type: DataTypes.STRING(200)
	},

	//推荐奖
	award: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0
	},
	//分佣
	commission: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0
	},
	//分红
	bonus: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0
	}
}, { tableName: 'app_order', sequelize });
Order.belongsTo(Car, {
	as: 'car',
	foreignKey: 'car_id'
});
Order.belongsTo(User, {
	as: 'buyer',
	foreignKey: 'user_id',
	//关闭外键检测（代客下单时，user_id=0）
	constraints: false
});
Order.belongsTo(User, {
	as: 'agency',
	foreignKey: 'draft_user_id',
	constraints: false
});
Order.belongsTo(User, {
	as: 'partner',
	foreignKey: 'partner_id',
	constraints: false
});

const Journal = sequelize.define('Journal', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	//类型 1：推荐奖（任何人），2：佣金（数字推广官），3：分红（平台合伙人）
	type: {
		type: DataTypes.TINYINT,
		defaultValue: 1
	},
	//金额
	amount: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0
	},
	//状态 0：未结算，1：已结算
	status: {
		type: DataTypes.TINYINT,
		defaultValue: 0
	}
}, { tableName: 'app_journal', sequelize });
Journal.belongsTo(User, {
	as: 'user',
	foreignKey: 'user_id'
});
User.hasMany(Journal, {
	as: 'journals',
	foreignKey: 'user_id'
});

Journal.belongsTo(Order, {
	as: 'order',
	foreignKey: 'order_id'
});

//提现
const Withdrawal = sequelize.define('Withdrawal', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	//提现金额
	amount: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0
	},
	//状态 0：未处理，1：已审核，2：驳回
	status: {
		type: DataTypes.TINYINT,
		defaultValue: 0
	},
	balance: {
		type: DataTypes.DECIMAL(10, 2),
		defaultValue: 0
	},
	//备注
	memo: {
		type: DataTypes.STRING(200)
	},

	//审核时间
	status_time: {
		type: DataTypes.DATE
	},
	//审核意见
	reason: {
		type: DataTypes.STRING(200)
	},
	bank: {
		type: DataTypes.STRING(200)
	},
	//户名
	bank_account: {
		type: DataTypes.STRING(100)
	},
	//卡号
	bank_account_no: {
		type: DataTypes.STRING(200)
	}
}, { tableName: 'app_withdrawal', sequelize });
Withdrawal.belongsTo(User, {
	as: 'user',
	foreignKey: 'user_id'
});

//开户行
/*
Withdrawal.belongsTo(Dictionary, {
	as: 'bank',
	foreignKey: 'bank_id'
});
*/

//平台合伙人地区
const UserRegion = sequelize.define('UserRegion', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	user_id: {
		type: DataTypes.INTEGER
	},
	city_id: {
		type: DataTypes.JSON
	},
	_city_id: {
		type: DataTypes.INTEGER
	},
	category_id: {
		type: DataTypes.INTEGER
	}
}, { tableName: 'app_user_region', sequelize });
User.hasMany(UserRegion, {
	as: 'regions',
	foreignKey: 'user_id'
});
UserRegion.belongsTo(User, {
	as: 'user',
	foreignKey: 'user_id'
});

//数字推广官申请
const UserPromoter = sequelize.define('UserPromoter', {
	id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
	fullname: {
		type: DataTypes.STRING(50)
	},
	phone: {
		type: DataTypes.STRING(11)
	},
	car_type: {
		type: DataTypes.STRING(200)
	},
	sale_quantity: {
		type: DataTypes.STRING(200)
	},
	sale_way: {
		type: DataTypes.STRING(200)
	},
	search_engine: {
		type: DataTypes.STRING(200)
	},
	we_media: {
		type: DataTypes.STRING(200)
	},
	team: {
		type: DataTypes.STRING(200)
	},
	channel: {
		type: DataTypes.STRING(200)
	},
	interest: {
		type: DataTypes.STRING(200)
	},
	doubt: {
		type: DataTypes.STRING(200)
	},
}, { tableName: 'app_user_promoter', sequelize });
UserPromoter.belongsTo(User, {
	as: 'user',
	foreignKey: 'user_id'
});

//初始化所有表格
sequelize.sync({ force: false, alter: true });

exports = module.exports = {
	sequelize,
	AccessToken,

	User,
	Profile,
	Dictionary,
	Region,
	Config,
	Industry,
	Article,

	School,
	SchoolClass,

	Doc,

	Car,
	CarModel,

	Station,

	Role,
	Module,

	Coupon,
	UserCoupon,

	Order,
	Journal,
	Withdrawal,

	UserRegion,
	UserPromoter
}
